package cn.cleanarch.infra.idp.pms.config;

import cn.cleanarch.infra.idp.pms.constants.ApiPathConstants;
import cn.cleanarch.infra.idp.pms.constants.StorageConstants;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * Web配置类
 */
@EnableWebMvc
@Configuration
public class BaseWebConfiguration implements WebMvcConfigurer {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(new MappingJackson2HttpMessageConverter(objectMapper()));
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 配置设计文件预览的静态资源路径
//        registry.addResourceHandler("/design-html-preview")
//                .addResourceLocations("file:" + StorageConstants.EXTRACT_BASE_PATH + "/")
//                .setCachePeriod(0);
    }

    private ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        
        // 注册JavaTime模块
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        
        // 添加LocalDateTime序列化器，格式为yyyy-MM-dd HH:mm:ss
        javaTimeModule.addSerializer(LocalDateTime.class, 
            new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        
        // 添加LocalDateTime反序列化器
        javaTimeModule.addDeserializer(LocalDateTime.class, 
            new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        
        objectMapper.registerModule(javaTimeModule);

        // 关闭未知属性检查
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        // 配置日期时间序列化格式
        objectMapper.findAndRegisterModules();
        return objectMapper;
    }
}